<template>
    <div>
        <CommonList :hasListHead="!isRanking" :table-data="jobList" :enable-export="true" :enable-column-btn="true"
            :column-list="columnList" :total-count="jobList.length" :use-select="false" :filterObjList="filterDataList"
            filter-field-name="className" :resizable="true" :show-default-op-btns="false" :show-edit-op-btns="false"
            :show-del-op-btns="false">
            <template #otherbtns>

                <el-switch v-model="autoRefresh" active-text="自动刷新" @change="onRefreshChange" v-if="isInExaming" />
                <el-button type="primary" @click="resetUserInfos">重置用户信息</el-button>

                <el-button type="warning" @click="recalAllMarks">重算成绩</el-button>
            </template>
            <template #opColumn="{ row }">
                <el-button type="warning" size="small" @click="showJobDetail(row)"
                    v-if="isTeacherOrAdmin">答题详情</el-button>
            </template>
        </CommonList>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted,watch } from 'vue'
// import { DataColumn } from '/@/models/column';
import { Job, QuestionGroup } from "/@/models/index";

import { QuestionGroupUrlSet, JobUrlSet } from "/@/models/urlset";
import { isBeforeTheTime } from "/@/utils/tool";
// import { JobUrlSet } from "/@/models/urlset";
import { QuizJobColumns, RankingJobColumns, netUtil } from '/@/models/columndata';
// import TableList from '/@/common/components/tablelist.vue';
import {
    getJobList, getRankingJobList, resetJobList, resetJobListCache, recaljobmarks

} from "/@/request/newapi";
import { ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { Role, QuestionGroupType } from '/@/models/enum';
//import emitter from "/@/utils/eventbus";
import { RoleCheck } from '/@/utils/rolecheck';
const { isTeacherOrAdmin } = RoleCheck()

const route = useRoute()

const qGroup = ref<QuestionGroup>()

const router = useRouter()

const jobs = ref<Job[]>([])
const autoRefresh = ref(false)
let gid = ''
const timer = ref()
const showJobDetail = (row) => {
    // console.log(row)
    //这里应该getSingleJob，从服务器读取

    //跳转到对应页面

    // emitter.emit('showJobDetail', row)//如何显示答题详情
    // const url = router.resolve({
    //     path: '/quiz/' + route.params['gid'],
    //     query: {
    //         session_id: row.session_id
    //     }
    // });
    console.log(url.href);  // 输出为#/test-url
    // 打开新窗口
    window.open(url.href);
}

const onRefreshChange = () => {
    if (autoRefresh.value && !timer.value) {//切换到自动刷新
        timer.value = setInterval(async () => {
            await getJobListFromServer(gid)
        }, 10000)//10秒刷新一次！！
    } else {
        clearInterval(timer.value)
        timer.value = null
    }
}

const resetUserInfos = async () => {

    const result = await ElMessageBox.confirm(
        '这将重置列表中的用户信息！！确定吗？',
        '特别警告！',
        {
            confirmButtonText: '确定重置',
            cancelButtonText: '取消',
            type: 'warning',
        }
    );
    if (result) {
        const gid = route.params['gid']
        const r1 = await resetJobList({ gid })
        resetJobListCache(gid)
        const result2 = await netUtil.getList<Job>(JobUrlSet, { gid })
        // debugger
        if (!result2.errno) {
            if (result2.listData) {
                jobs.value = result2.listData
            } else
                jobs.value = result2

        } else {
            ElMessageBox.alert(result2.message)
        }
    }

}

const recalAllMarks = async () => {

    const result = await ElMessageBox.confirm(
        '这将重新计算所有成绩！！确定吗？',
        '特别警告！',
        {
            confirmButtonText: '确定重新计算',
            cancelButtonText: '取消',
            type: 'warning',
        }
    );
    if (result) {
        const gid = route.params['gid']
        await recaljobmarks({ gid })
        resetJobListCache(gid)
        const result2 = await netUtil.getList<Job>(JobUrlSet, { gid })
        // debugger
        if (!result2.errno) {
            if (result2.listData) {
                jobs.value = result2.listData
            } else
                jobs.value = result2

        } else {
            ElMessageBox.alert(result2.message)
        }
    }

}

const filterDataList = ref([])


const ClassNames = computed(() => {
    const cnames: string[] = []
    if (jobs.value && jobs.value.length) {
        jobs.value.forEach(item => {
            if (item.className && cnames.indexOf(item.className) == -1) {
                cnames.push(item.className)
            }
        })
    }

    return cnames
})

watch(jobs, () => {
    // 这个函数只会在 tableData 第一次变化时执行
    const fdata: FilterData = { datalist: ClassNames.value, isMultiple: true,  onlyLocal: true, placeholder: '班级', filterFieldName: 'className', selectedlist: [] }

    filterDataList.value.push(fdata)

}, { once: true });
const isInExaming = computed(() => {
    
    if (qGroup.value && qGroup.value.groupType == QuestionGroupType.Exam && isBeforeTheTime(qGroup.value.canStartTime) == false && isBeforeTheTime(qGroup.value.canStartTime, qGroup.value.limitMinutes * 60)) { //截止时间前
        return true
    } else {
        return false
    }
})
const isRanking = computed(() => {
    return rankingType.value && rankingType.value != 'all'
})
const columnList = computed(() => {
    if (rankingType.value) {
        return RankingJobColumns.value
    } else {
        return QuizJobColumns.value
    }
})
const jobList = computed(() => {
    let rankingList = []
    const rankingStr = rankingType.value
    if (rankingStr) {

        if (rankingStr == 'asc') {
            rankingList = jobs.value.sort((a, b) => { return a.score - b.score }).slice(0, 10)
        } else if (rankingStr == 'desc') {
            rankingList = jobs.value.slice(0, 10)
        } else {
            rankingList = jobs.value
        }
        return rankingList
    } else {


        return jobs.value
    }
})
const rankingType = ref('')

onMounted(async () => {
    gid = route.params['gid'] as string//有题组id,才有数据

    rankingType.value = route.query['rankingtype']

    qGroup.value = await netUtil.getEntity(QuestionGroupUrlSet, gid)

    if (qGroup.value && isInExaming) {//如果是考试监控，则需要定时刷新，应该有个开关
        await getJobListFromServer(gid)
        // timer.value = setInterval(async () => {
        //     await getJobListFromServer(gid)
        // }, 10000)//10秒刷新一次！！

    } else {//如果是查看成绩，则不需要，还可以使用缓存！
        if (rankingType.value) {
            JobUrlSet.getListApiUrl = '/q_api/job/rankinglist'
        } else {
            JobUrlSet.getListApiUrl = '/q_api/job/list'
        }
        const result = await netUtil.getList<Job>(JobUrlSet, { gid })

        if (result && !result.errno) {
            if (result.listData) {
                jobs.value = result.listData
            } else
                jobs.value = result

        } else {
            ElMessageBox.alert(result.message)
        }
    }

})

async function getJobListFromServer(gid) {
    let result = {}
    // debugger
    if (rankingType.value) {
        result = await getRankingJobList({ gid })

    } else {
        result = await getJobList({ gid })
    }
    if (result)
        jobs.value = result
}
</script>

<style scoped></style>